/**
 * 消息通知服务
 * 支持浏览器原生通知、推送通知等
 */
import notificationSettings from './settings/notification-settings.js'

class NotificationService {
  constructor() {
    this.isSupported = this.checkSupport()
    this.permission = 'default'
    this.notifications = []
    this.maxNotifications = 5
    this.autoCloseDelay = 5000 // 5秒后自动关闭
  }

  // 检查浏览器支持
  checkSupport() {
    return typeof Notification !== 'undefined'
  }

  // 请求通知权限
  async requestPermission() {
    if (!this.isSupported) {
      console.warn('浏览器不支持通知功能')
      return false
    }

    try {
      this.permission = await Notification.requestPermission()
      console.log('通知权限状态:', this.permission)
      return this.permission === 'granted'
    } catch (error) {
      console.error('请求通知权限失败:', error)
      return false
    }
  }

  // 显示通知
  async showNotification(title, options = {}) {
    // 检查通知设置
    const notificationType = options.data?.type || 'system'
    if (!notificationSettings.shouldShowNotification(notificationType)) {
      console.log('[NotificationService] 通知已被设置禁用:', notificationType)
      return null
    }
    
    if (!this.isSupported || this.permission !== 'granted') {
      console.warn('无法显示通知：权限不足或浏览器不支持')
      return null
    }

    try {
      // 应用声音和震动设置
      const silent = !notificationSettings.isSoundEnabled()
      const vibrate = notificationSettings.isVibrationEnabled() ? [200, 100, 200] : undefined
      
      const notification = new Notification(title, {
        icon: options.icon || '/static/logo.png',
        badge: options.badge || '/static/logo.png',
        body: options.body || '',
        tag: options.tag || 'default',
        requireInteraction: options.requireInteraction || false,
        silent: silent,
        vibrate: vibrate,
        timestamp: options.timestamp || Date.now(),
        data: options.data || {}
      })

      // 添加到通知列表
      this.notifications.push(notification)

      // 限制通知数量
      if (this.notifications.length > this.maxNotifications) {
        const oldNotification = this.notifications.shift()
        oldNotification.close()
      }

      // 自动关闭
      if (options.autoClose !== false) {
        setTimeout(() => {
          notification.close()
        }, this.autoCloseDelay)
      }

      // 点击事件
      notification.onclick = (event) => {
        event.preventDefault()
        this.handleNotificationClick(notification, event)
        notification.close()
      }

      // 关闭事件
      notification.onclose = () => {
        this.removeNotification(notification)
      }

      return notification

    } catch (error) {
      console.error('显示通知失败:', error)
      return null
    }
  }

  // 处理通知点击
  handleNotificationClick(notification, event) {
    const data = notification.data || {}
    
    // 根据通知类型执行不同操作
    switch (data.type) {
      case 'chat':
        // 跳转到聊天页面
        uni.navigateTo({
          url: `/pages/chat/chat?userId=${data.userId}&userName=${data.userName}`
        })
        break
        
      case 'friend_request':
        // 跳转到好友请求页面
        uni.navigateTo({
          url: '/pages/friends/requests/requests'
        })
        break
        
      case 'points':
        // 跳转到积分页面
        uni.navigateTo({
          url: '/pages/points/points'
        })
        break
        
      default:
        // 默认跳转到首页
        uni.switchTab({
          url: '/pages/index/index'
        })
    }
  }

  // 移除通知
  removeNotification(notification) {
    const index = this.notifications.indexOf(notification)
    if (index > -1) {
      this.notifications.splice(index, 1)
    }
  }

  // 关闭所有通知
  closeAllNotifications() {
    this.notifications.forEach(notification => {
      notification.close()
    })
    this.notifications = []
  }

  // 显示聊天消息通知
  async showChatNotification(senderName, message, userId) {
    return await this.showNotification(
      `来自 ${senderName} 的消息`,
      {
        body: message,
        icon: '/static/logo.png',
        tag: `chat_${userId}`,
        data: {
          type: 'message',  // 使用message类型以匹配设置
          userId: userId,
          userName: senderName
        }
      }
    )
  }

  // 显示好友请求通知
  async showFriendRequestNotification(senderName, userId) {
    return await this.showNotification(
      '新的好友请求',
      {
        body: `${senderName} 想要添加您为好友`,
        icon: '/static/logo.png',
        tag: `friend_request_${userId}`,
        data: {
          type: 'friendRequest',  // 使用friendRequest类型以匹配设置
          userId: userId,
          userName: senderName
        }
      }
    )
  }

  // 显示积分变动通知
  async showPointsNotification(points, reason) {
    const isPositive = points > 0
    return await this.showNotification(
      isPositive ? '积分增加' : '积分减少',
      {
        body: `${isPositive ? '+' : ''}${points} 积分 - ${reason}`,
        icon: '/static/logo.png',
        tag: 'points_update',
        data: {
          type: 'points',
          points: points,
          reason: reason
        }
      }
    )
  }

  // 显示系统通知
  async showSystemNotification(title, message, data = {}) {
    return await this.showNotification(
      title,
      {
        body: message,
        icon: '/static/logo.png',
        tag: 'system',
        data: {
          type: 'system',
          ...data
        }
      }
    )
  }

  // 显示游戏通知
  async showGameNotification(title, message, gameType) {
    return await this.showNotification(
      title,
      {
        body: message,
        icon: '/static/logo.png',
        tag: `game_${gameType}`,
        data: {
          type: 'game',
          gameType: gameType
        }
      }
    )
  }

  // 获取通知权限状态
  getPermissionStatus() {
    return this.permission
  }

  // 检查是否支持通知
  isNotificationSupported() {
    return this.isSupported
  }

  // 设置通知配置
  setConfig(config) {
    if (config.maxNotifications) {
      this.maxNotifications = config.maxNotifications
    }
    if (config.autoCloseDelay) {
      this.autoCloseDelay = config.autoCloseDelay
    }
  }
  
  // 获取未读通知数量
  getUnreadCount() {
    try {
      const notifications = JSON.parse(uni.getStorageSync('notifications') || '[]')
      return notifications.filter(n => !n.isRead).length
    } catch (error) {
      console.error('获取未读通知数量失败:', error)
      return 0
    }
  }
  
  // 更新通知角标
  updateUnreadBadge() {
    try {
      const count = this.getUnreadCount()
      
      // TabBar 页面索引（聊天页面是第3个，索引为2）
      const tabIndex = 2
      
      // 更新tabBar红点
      if (count > 0) {
        // 设置红点（静默失败，避免在非TabBar页面报错）
        uni.showTabBarRedDot({
          index: tabIndex,
          fail: () => {
            // 静默处理错误
          }
        })
        
        // 如果支持设置badge数字，则设置数字
        if (typeof uni.setTabBarBadge === 'function') {
          uni.setTabBarBadge({
            index: tabIndex,
            text: count > 99 ? '99+' : String(count),
            fail: () => {
              // 静默处理错误
            }
          })
        }
      } else {
        // 隐藏红点
        uni.hideTabBarRedDot({
          index: tabIndex,
          fail: () => {
            // 静默处理错误
          }
        })
        
        // 移除badge
        if (typeof uni.removeTabBarBadge === 'function') {
          uni.removeTabBarBadge({
            index: tabIndex,
            fail: () => {
              // 静默处理错误
            }
          })
        }
      }
      
      return count
    } catch (error) {
      // 捕获任何错误，避免影响程序运行
      console.warn('更新通知角标时出错（非关键错误）:', error)
      return 0
    }
  }
  
  // 保存通知到本地存储
  saveNotification(notification) {
    try {
      // 获取现有通知
      const notifications = JSON.parse(uni.getStorageSync('notifications') || '[]')
      
      // 添加新通知
      notifications.unshift(notification)
      
      // 限制通知数量
      const maxStoredNotifications = 50
      if (notifications.length > maxStoredNotifications) {
        notifications.splice(maxStoredNotifications)
      }
      
      // 保存通知
      uni.setStorageSync('notifications', JSON.stringify(notifications))
      
      // 更新通知角标
      this.updateUnreadBadge()
      
      console.log('通知已保存:', notification)
    } catch (error) {
      console.error('保存通知失败:', error)
    }
  }
}

// 导出单例
export default new NotificationService()
